<script>
import { createProps } from '@/utils'
import SubFormRelationButton from '@comp/hhd/design/FormField/subForm/SubFormRelationButton.vue'

export default {
  name: 'SubFormRelationButtons',
  props: {
    context: createProps(Object, () => undefined),
    subForm: createProps(Object, () => undefined)
  },
  render(h) {
    let res = this.renderButtons()
    if (!res || !res.length) return undefined
    return this.wrapperButtons(h, res)
  },
  methods: {
    wrapperButtons(h, res) {
      return h('span', res)
    },
    renderButtons() {
      let formDefinition = this.context && this.context.formDefinition && this.context.formDefinition || undefined
      if (!formDefinition) return undefined
      let relations = this.context && this.context.formDefinition && this.context.formDefinition.relations || []
      let res = []
      relations.forEach(relation => {
        let manuals = relation.manuals || []
        manuals.forEach(manual => {
          let fieldBinds = manual.fieldBinds || []
          if (fieldBinds
            && fieldBinds.length
            && fieldBinds[0].sourceFormId === this.subForm.id
            && manual.manualSelectorSubFormButtonName) {
            res.push(this.renderButton(relation, manual))
          }
        })
      })
      return res
    },
    renderButton(relation, manual) {
      let h = this.$createElement
      return h(SubFormRelationButton, {
        props: {
          relation, manual,
          context: this.context,
          subForm: this.subForm
        }
      })
    }
  }
}
</script>